package com.saturday.auth.aspect;

import com.saturday.auth.util.ServletUtils;
import com.saturday.common.constants.CommonConsts;
import com.saturday.common.exception.BusinessException;
import com.saturday.common.exception.UserContextLoseException;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * 内部服务调用验证处理
 * <p>
 * 通过配置cloud.inner.service.auth.opened=true对整个服务下固定包路径下的内部服务进行权限处理
 *
 * @author wangguodong
 */
@Aspect
@Component
@ConditionalOnProperty(name = "cloud.inner.service.auth.opened", havingValue = "true")
public class InnerAuthAspect implements Ordered {

    @Pointcut("execution(* com.saturday.*.provide..*.*(..))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object innerAround(ProceedingJoinPoint point) throws Throwable {
        String source = ServletUtils.getRequest().getHeader(CommonConsts.FEIGN_CLIENT_KEY);
        // 内部请求验证
        if (!StringUtils.equals("true", source)) {
            throw new BusinessException("没有内部访问权限，不允许访问");
        }

        String sessionId = ServletUtils.getRequest().getHeader(CommonConsts.USER_SESSIONID);
        String token = ServletUtils.getRequest().getHeader(CommonConsts.HTTP_HEADER_ACCESS_TOKEN);
        if (StringUtils.isEmpty(sessionId) && StringUtils.isEmpty(token)) {
            throw new UserContextLoseException("用户信息为空，禁止访问");
        }

        return point.proceed();
    }

    /**
     * 确保在权限认证aop执行前执行
     */
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 2;
    }
}
